using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

namespace MVCWeekOne.Controllers
{
	public class ProductionController : Controller
	{
		private readonly IConfiguration _configuration;

		public ProductionController(IConfiguration configuration)
		{
			_configuration = configuration;
		}

		// GET: Production/WorkReport - 重定向到正确的报工页面
		public IActionResult WorkReport()
		{
			return RedirectToAction("Index", "WorkReport");
		}

		// GET: Production/CompletionSheet
		public IActionResult CompletionSheet()
		{
			ViewBag.ReadApiUrl = _configuration["ApiSettings:ReadApiUrl"] ?? "http://localhost:5089/api";
			ViewBag.WriteApiUrl = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
			ViewBag.CurrentUserId = GetCurrentUserId();
			ViewBag.CurrentUserName = GetCurrentUserName();
			ViewBag.Token = HttpContext.Session.GetString("Token") ?? string.Empty;
			return View();
		}

		// GET: Production/ProductionReport - 生产报表
		public IActionResult ProductionReport()
		{
			ViewBag.ReadApiUrl = _configuration["ApiSettings:ReadApiUrl"] ?? "http://localhost:5089/api";
			ViewBag.WriteApiUrl = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
			ViewBag.CurrentUserId = GetCurrentUserId();
			ViewBag.CurrentUserName = GetCurrentUserName();
			ViewBag.Token = HttpContext.Session.GetString("Token") ?? string.Empty;
			return View();
		}

		/// <summary>
		/// 获取当前登录用户ID（Session/Claims，默认1）
		/// </summary>
		private int GetCurrentUserId()
		{
			var userId = HttpContext.Session.GetString("UserId");
			if (!string.IsNullOrEmpty(userId) && int.TryParse(userId, out int id))
			{
				return id;
			}

			var userClaim = User.FindFirst("UserId");
			if (userClaim != null && int.TryParse(userClaim.Value, out int claimId))
			{
				return claimId;
			}

			return 1;
		}

		/// <summary>
		/// 获取当前登录用户名（Session/Claims，默认"当前用户"）
		/// </summary>
		private string GetCurrentUserName()
		{
			var userName = HttpContext.Session.GetString("UserName");
			if (!string.IsNullOrEmpty(userName))
			{
				return userName;
			}

			var userClaim = User.FindFirst("UserName");
			if (userClaim != null)
			{
				return userClaim.Value;
			}

			return "当前用户";
		}
	}
} 